package mcia_administrative;

import java.io.*;
import javax.swing.JFileChooser;
import java.util.*;
import java.util.zip.*;
import javax.swing.UIManager;

/*
 * WelcomeScreen.java - shows first screen with three options to choose:
 * new project, editing existing project or importing .zip project file.
 *
 * @author MCIA
 */
public class WelcomeScreen extends javax.swing.JFrame {

    static final String strDirectory2 = "temp2";                                //defining name for temporary directory 1
    static File temp2 = new File(strDirectory2);                                //file variable of this above
    static final String strDirectory = "temp";                                  //defining name for temporary directory 2
    static File temp = new File(strDirectory);                                  //file variable of this above
    static final String strDirectoryProjectConfig = "scenes";                   //directory for storing .txt files that are keeping current project variables
    File file2G;                                                                //file used for zipping
    private int BUFFER = 2048;                                                  //setting buffer size for file read

    public WelcomeScreen() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        ClosingConfirmation = new javax.swing.JFrame();
        jPanel5 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        OK = new javax.swing.JButton();
        Cancel = new javax.swing.JButton();
        fileChooser = new javax.swing.JFileChooser();
        fileChooser2 = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        newProjectButton = new javax.swing.JButton();
        existingProjectButton = new javax.swing.JButton();
        quitButton = new javax.swing.JButton();
        openProjectFileButton = new javax.swing.JButton();

        ClosingConfirmation.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        ClosingConfirmation.setTitle("Quit Application?");
        ClosingConfirmation.setAlwaysOnTop(true);
        ClosingConfirmation.setBounds(new java.awt.Rectangle(500, 350, 0, 0));
        ClosingConfirmation.setMaximizedBounds(new java.awt.Rectangle(300, 300, 232, 97));
        ClosingConfirmation.setMinimumSize(new java.awt.Dimension(232, 110));
        ClosingConfirmation.setName("closeConfirmation"); // NOI18N
        ClosingConfirmation.setResizable(false);

        jPanel5.setPreferredSize(new java.awt.Dimension(320, 97));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel3.setText("Do you really want to quit?");

        OK.setText("Quit");
        OK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OKActionPerformed(evt);
            }
        });

        Cancel.setText("Cancel");
        Cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(OK, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(Cancel))
                    .addComponent(jLabel3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addComponent(jLabel3)
                .addGap(14, 14, 14)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(OK)
                    .addComponent(Cancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout ClosingConfirmationLayout = new javax.swing.GroupLayout(ClosingConfirmation.getContentPane());
        ClosingConfirmation.getContentPane().setLayout(ClosingConfirmationLayout);
        ClosingConfirmationLayout.setHorizontalGroup(
            ClosingConfirmationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ClosingConfirmationLayout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );
        ClosingConfirmationLayout.setVerticalGroup(
            ClosingConfirmationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ClosingConfirmationLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.setCurrentDirectory(new java.io.File("C:\\Users\\Jacek\\Downloads\\Projekt erazmusowy\\MCI\\Kamil_GUI\\test"));
        fileChooser.setFileFilter(new MyCustomFilter());

        fileChooser2.setAcceptAllFileFilterUsed(false);
        fileChooser2.setCurrentDirectory(new java.io.File("C:\\Users\\Jacek\\Downloads\\Projekt erazmusowy\\MCI\\Kamil_GUI\\test"));
        fileChooser2.setDialogTitle("Choose txt file");
        fileChooser2.setFileFilter(new MyCustomFilter2());

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("MCIA LightControl");
        setBounds(new java.awt.Rectangle(200, 20, 800, 600));
        setMaximizedBounds(new java.awt.Rectangle(0, 0, 800, 600));
        setMinimumSize(new java.awt.Dimension(800, 600));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel2.setText("Welcome");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
        );

        jPanel3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Lights Project Manager");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 784, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
                .addContainerGap())
        );

        newProjectButton.setText("Make New Project");
        newProjectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newProjectButtonActionPerformed(evt);
            }
        });

        existingProjectButton.setText("Edit Existing Project");
        existingProjectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                existingProjectButtonActionPerformed(evt);
            }
        });

        quitButton.setText("Quit");
        quitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quitButtonActionPerformed(evt);
            }
        });

        openProjectFileButton.setText("Open Project File ...");
        openProjectFileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openProjectFileButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(645, Short.MAX_VALUE)
                .addComponent(quitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(25, 25, 25))
            .addGroup(layout.createSequentialGroup()
                .addGap(289, 289, 289)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(openProjectFileButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(existingProjectButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(newProjectButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE))
                .addContainerGap(293, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(152, 152, 152)
                .addComponent(newProjectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(existingProjectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(openProjectFileButton, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 100, Short.MAX_VALUE)
                .addComponent(quitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
    }//GEN-LAST:event_formKeyPressed

    private void newProjectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProjectButtonActionPerformed
        //zeroing variables for new project
        Main.allUnits.removeAll(Main.allUnits);
        Main.allUnits.add(0, new ArrayList<String[]>());
        Main.floorImages.removeAll(Main.floorImages);
        Main.floorImages.add(0, "-");
        Main.floorDescriptions.removeAll(Main.floorDescriptions);
        Main.floorDescriptions.add(0, "");
        Main.allLights.removeAll(Main.allLights);
        Main.globalScenes.removeAll(Main.globalScenes);
        Main.globalSceneName.removeAll(Main.globalSceneName);

        //emptying temp
        emptyDirectory(temp);

        //going to DesktopFloorDesign
        DesktopFloorDesign dsktp = new DesktopFloorDesign();
        Main.changeFrame(dsktp);
    }//GEN-LAST:event_newProjectButtonActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        ClosingConfirmation.setVisible(true);
        //saving variables to file to remember them later
        saveVariablesToFile();
    }//GEN-LAST:event_formWindowClosing

    private void OKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKActionPerformed
        //exit program
        this.dispose();
        System.exit(0);
}//GEN-LAST:event_OKActionPerformed

    private void CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelActionPerformed
        //hide closingConfirmation
        ClosingConfirmation.dispose();
}//GEN-LAST:event_CancelActionPerformed

    private void existingProjectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_existingProjectButtonActionPerformed
        //loading variables from txt files
        if (Main.allUnits.size() <= 1) {
            loadVariablesFromFile();
        }

        //going to DesktopFloorDesign
        DesktopFloorDesign dsktp = new DesktopFloorDesign();
        Main.changeFrame(dsktp);
    }//GEN-LAST:event_existingProjectButtonActionPerformed

    private void quitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitButtonActionPerformed
        //showing closing confirmation and saving files
        ClosingConfirmation.setVisible(true);
        saveVariablesToFile();
    }//GEN-LAST:event_quitButtonActionPerformed

    private void openProjectFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openProjectFileButtonActionPerformed
        //this function is made for opening the file chooser and loading .zip project file
        emptyDirectory(temp2);

        int returnVal = fileChooser2.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file2 = fileChooser2.getSelectedFile();
            file2G = file2;

            System.out.println("File accessed: " + file2.getAbsolutePath());
        } else {
            System.out.println("File access cancelled by user.");
        }
        //creating directory for storing files
        try {
            boolean success = (temp2).mkdir();
            if (success) {
                System.out.println("Directory " + strDirectory2 + " created:" + temp2.getAbsolutePath());
            } else {
                System.out.println("Directory: " + strDirectory2 + " not created, probably it exists.");
            }
        } catch (Exception e) {
            //catch exception if any
            System.err.println("Error: " + e.getMessage());
            return;
        }
        //---------------------unzip----------------------------
        try {
            BufferedOutputStream dest = null;
            BufferedInputStream is = null;
            ZipEntry entry;
            ZipFile zipfile = new ZipFile(file2G);
            Enumeration e = zipfile.entries();
            while (e.hasMoreElements()) {
                entry = (ZipEntry) e.nextElement();
                System.out.println("Extracting: " + entry);
                is = new BufferedInputStream(zipfile.getInputStream(entry));
                int count;
                byte data[] = new byte[BUFFER];
                File temporary = new File("temp2", entry.getName());
                FileOutputStream fos = new FileOutputStream(temporary);
                dest = new BufferedOutputStream(fos, BUFFER);
                while ((count = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
                is.close();
            }
        } catch (Exception e) {
            System.out.println("Error: " + e);
            return;
        }
        //-----------------------end of unzipping--------------------

        //loading project variables from extracted files
        loadProjectFromFiles();

        //going to DesktopFloorDesign
        DesktopFloorDesign dsktp = new DesktopFloorDesign();
        Main.changeFrame(dsktp);

    }//GEN-LAST:event_openProjectFileButtonActionPerformed

    public void loadProjectFromFiles() {
        //function that allows to load project variables from extracted .zip files
        Main.floorDescriptions.removeAll(Main.floorDescriptions);
        Main.globalSceneName.removeAll(Main.globalSceneName);
        Main.globalScenes.removeAll(Main.globalScenes);
        Main.allUnits.removeAll(Main.allUnits);
        Main.allUnits.add(new ArrayList<String[]>());
        Main.floorImages.removeAll(Main.floorImages);
        Main.floorImages.add(0, "");

        File descFile = new File("temp2", "floorDesc.txt");
        if (descFile.exists()) {
            try {
                System.out.println("Sucessfully accessed txt file: " + descFile);
                FileReader fr = new FileReader(descFile);
                BufferedReader br = new BufferedReader(fr);
                String dbRecord;
                int lineCount = 0;

                while ((dbRecord = br.readLine()) != null) {
                    //accessing file with floor descriptions
                    StringTokenizer st = new StringTokenizer(dbRecord, ";");

                    while (st.hasMoreTokens()) {
                        lineCount++;
                        String token = st.nextToken();
                        if (st.hasMoreTokens()) {
                            String token2 = st.nextToken();
                            Main.floorDescriptions.add(token2);
                        } else {
                            Main.floorDescriptions.add("");
                        }
                    }
                }
            } catch (Exception ex) {
                System.out.println("Error with file: " + ex + " Filename: floorDesc.txt");
                return;
            }
        } else {
            //file doesn't exits
            System.out.println("WARNING: File with floor descriptions not found.");
        }

        String files[] = temp2.list();
        for (int i = 0; i < files.length; i++) {

            int gsFirstLine = 0;
            File sourcefile = new File("temp2", files[i]);

            if (files[i].endsWith(".txt") && !files[i].startsWith("LS") && !files[i].startsWith("CL") && !files[i].startsWith("GS") && !files[i].startsWith("floor")) {
                Main.allUnits.add(new ArrayList<String[]>());
                Main.floorImages.add("");
            }

            if (sourcefile.getName().endsWith(".txt")) {
                //what to do with txt file
                try {
                    System.out.println("Sucessfully accessed txt file: " + sourcefile);
                    FileReader fr = new FileReader(sourcefile);
                    BufferedReader br = new BufferedReader(fr);

                    int floorNo, clNo, lightNo;
                    String dbRecord;
                    //reading txt config file

                    while ((dbRecord = br.readLine()) != null) {
                        if (files[i].length() > 2 && files[i].substring(0, 2).equals("LS")) {
                            try {
                                File f1 = new File(strDirectory2, files[i]);
                                File f2 = new File(strDirectory, files[i]);
                                if (!f2.exists()) {
                                    f2.createNewFile();
                                }
                                InputStream in = new FileInputStream(f1);

                                OutputStream out = new FileOutputStream(f2);

                                byte[] buf = new byte[1024];
                                int len;
                                while ((len = in.read(buf)) > 0) {
                                    out.write(buf, 0, len);
                                }
                                in.close();
                                out.close();
                            } catch (FileNotFoundException ex) {
                                System.out.println(ex.getMessage() + " in the specified directory.");
                                System.exit(0);
                            } catch (IOException e) {
                                System.out.println(e.getMessage());
                            }
                        } else if (files[i].length() > 2 && files[i].substring(0, 2).equals("GS")) {
                            //for Global Scene files----------------------------------------------------------------------------
                            StringTokenizer st = new StringTokenizer(dbRecord, ";");

                            while (st.hasMoreTokens()) {
                                try {
                                    if (gsFirstLine == 0) {
                                        String token0 = st.nextToken(); //tutaj masz nazwę sceny globalnej
                                        //inserting scene into variables
                                        Main.globalSceneName.add(token0);
                                        Main.globalScenes.add(new ArrayList<String[]>());
                                        gsFirstLine = 1;
                                    } else {
                                        int floorNumber = Integer.parseInt(st.nextToken());
                                        int clNumber = Integer.parseInt(st.nextToken());
                                        String clName2 = "CL " + floorNumber + "." + clNumber;
                                        String lsName = st.nextToken(); //tutaj masz nazwę sceny lokalnej
                                        String timeSch = st.nextToken();
                                        //inserting into arraylist
                                        String[] put = new String[]{clName2, lsName, timeSch};
                                        Main.globalScenes.get(Main.globalScenes.size() - 1).add(put);
                                    }
                                } catch (Exception ex) {
                                    System.out.println("Error with parsing global scene file: " + files[i] + " Message: " + ex);
                                }
                            }
                        } else if (files[i].length() > 2 && !files[i].equals("floorDesc.txt")) {
                            //accessing other txt file (with Floor or CL)-------------------------------------------------------
                            StringTokenizer st = new StringTokenizer(dbRecord, ";");

                            String floor = st.nextToken();
                            String clName = st.nextToken();
                            String Light = st.nextToken();
                            String X = st.nextToken();
                            String Y = st.nextToken();

                            floorNo = Integer.parseInt(floor);
                            clNo = Integer.parseInt(clName);
                            lightNo = Integer.parseInt(Light);

                            int countDots = files[i].indexOf(".");
                            int countDots2 = files[i].substring(Math.abs(countDots) + 1).indexOf(".");

                            if (countDots2 > 0) { //CL file
                                //putting data into database
                                String token = "CL " + floorNo + "." + clNo;
                                String token2 = "Light " + floorNo + "." + clNo + "." + lightNo;
                                String[] put = new String[]{token, token2, X, Y, ""};
                                Main.allLights.add(put);
                            } else { //floor file (with possible CLs)
                                //only once adding floor
                                String token = "CL " + floorNo + "." + clNo;
                                String token2 = X;
                                String token3 = Y;
                                String[] put = new String[]{token, token2, token3};
                                Main.allUnits.get(floorNo).add(put);
                            }
                        }
                    }
                } catch (Exception ex) {
                    System.out.println("Error with file: " + ex + " Filename: " + files[i]);
                    return;
                }
            }
        }

        int countImgFiles = 0;
        for (int i = 0; i < files.length; i++) {
            File sourcefile = new File("temp2", files[i]);

            if (sourcefile.getName().endsWith(".jpg")) {
                int countDots = files[i].indexOf(".");
                int countDots2 = files[i].substring(Math.abs(countDots) + 1).indexOf(".");
                System.out.println("Sucessfully accessed jpg file: " + sourcefile);
                if (countDots2 > 0) { //CL image
                    String toCheck = files[i].substring(3, 6);
                    for (int j = 0; j < Main.allLights.size(); j++) {
                        String temporary = "Light " + toCheck + ".1";
                        if (temporary.equals(Main.allLights.get(j)[1])) {
                            Main.allLights.get(j)[4] = sourcefile.getAbsolutePath();
                        }
                    }
                } else {  //floor image
                    StringTokenizer st = new StringTokenizer(files[i], ".");
                    String var = st.nextToken();
                    int floorNo2 = Integer.parseInt(var);
                    System.out.println("Floor number:" + floorNo2);
                    Main.floorImages.set(floorNo2, sourcefile.getAbsolutePath());
                    countImgFiles++;
                }
            }
        }
    }

    public void loadVariablesFromFile() {
        //getting data from current project .txt files into variables
        //loading lights
        File descFile = new File(strDirectoryProjectConfig, "currentProjectLights.txt");
        try {
            System.out.println("Sucessfully accessed txt file: " + descFile);
            FileReader fr = new FileReader(descFile);
            BufferedReader br = new BufferedReader(fr);
            String dbRecord;
            int lineCount = 0;

            while ((dbRecord = br.readLine()) != null) {
                //accessing file
                StringTokenizer st = new StringTokenizer(dbRecord, ";");

                while (st.hasMoreTokens()) {
                    lineCount++;
                    String token = st.nextToken();
                    String token2 = st.nextToken();
                    String token3 = st.nextToken();
                    String token4 = st.nextToken();
                    if (st.hasMoreTokens()) {
                        String token5 = st.nextToken();
                        String[] put = new String[]{token, token2, token3, token4, token5};
                        Main.allLights.add(put);
                    } else {
                        String[] put = new String[]{token, token2, token3, token4, ""};
                        Main.allLights.add(put);
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println("Error with file: " + ex + " Filename: currentProjectLights.txt");
        }

        //loading units
        File descFile2 = new File(strDirectoryProjectConfig, "currentProjectUnits.txt");
        try {
            System.out.println("Sucessfully accessed txt file: " + descFile2);
            FileReader fr = new FileReader(descFile2);
            BufferedReader br = new BufferedReader(fr);
            String dbRecord;
            int lineCount = 0;
            int floorCount = -1;

            Main.allUnits.removeAll(Main.allUnits);

            while ((dbRecord = br.readLine()) != null) {
                //accessing file
                StringTokenizer st = new StringTokenizer(dbRecord, ";");

                while (st.hasMoreTokens()) {
                    lineCount++;
                    String token = st.nextToken();
                    if (token.equals("NextFloor")) {
                        floorCount++;
                        Main.allUnits.add(new ArrayList<String[]>());
                    } else if (token.equals("deleted")) {
                        String[] deleted = new String[]{"deleted", "", "", "", ""};
                        Main.allUnits.get(floorCount).add(deleted);
                    } else {
                        String token2 = st.nextToken();
                        String token3 = st.nextToken();
                        String[] put = new String[]{token, token2, token3};
                        Main.allUnits.get(floorCount).add(put);
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println("Error with file: " + ex + " Filename: currentProjectUnits.txt");
        }

        //loading floor descriptions
        File descFile3 = new File(strDirectoryProjectConfig, "currentProjectDescriptions.txt");
        try {
            System.out.println("Sucessfully accessed txt file: " + descFile3);
            FileReader fr = new FileReader(descFile3);
            BufferedReader br = new BufferedReader(fr);
            String dbRecord;
            int lineCount = 0;

            Main.floorDescriptions.removeAll(Main.floorDescriptions);
            Main.floorDescriptions.add(0, "");

            while ((dbRecord = br.readLine()) != null) {
                //accessing file
                lineCount++;
                Main.floorDescriptions.add(dbRecord);
            }
        } catch (Exception ex) {
            System.out.println("Error with file: " + ex + " Filename: currentProjectDescriptions.txt");
        }

        //loading images
        File descFile4 = new File(strDirectoryProjectConfig, "currentProjectImages.txt");
        try {
            System.out.println("Sucessfully accessed txt file: " + descFile4);
            FileReader fr = new FileReader(descFile4);
            BufferedReader br = new BufferedReader(fr);
            String dbRecord;
            int lineCount = 0;

            Main.floorImages.removeAll(Main.floorImages);
            Main.floorImages.add(0, "");

            while ((dbRecord = br.readLine()) != null) {
                //accessing file
                lineCount++;
                Main.floorImages.add(dbRecord);
            }
        } catch (Exception ex) {
            System.out.println("Error with file: " + ex + " Filename: currentProjectImages.txt");
        }

        //loading free floors
        File descFile5 = new File(strDirectoryProjectConfig, "currentProjectFreeFloors.txt");
        try {
            System.out.println("Sucessfully accessed txt file: " + descFile5);
            FileReader fr = new FileReader(descFile5);
            BufferedReader br = new BufferedReader(fr);
            String dbRecord;
            int lineCount = 0;

            Main.freeFloorNumbers.removeAll(Main.freeFloorNumbers);

            while ((dbRecord = br.readLine()) != null) {
                //accessing file
                lineCount++;
                Main.freeFloorNumbers.add(Integer.parseInt(dbRecord));
            }
        } catch (Exception ex) {
            System.out.println("Error with file: " + ex + " Filename: " + descFile5);
        }

        //loading GS
        File descFile6 = new File(strDirectoryProjectConfig, "currentProjectGS.txt");
        try {
            System.out.println("Sucessfully accessed txt file: " + descFile6);
            FileReader fr = new FileReader(descFile6);
            BufferedReader br = new BufferedReader(fr);
            String dbRecord;
            int lineCount = 0;
            int GSCount = -1;

            Main.globalScenes.removeAll(Main.globalScenes);

            while ((dbRecord = br.readLine()) != null) {
                //accessing file
                StringTokenizer st = new StringTokenizer(dbRecord, ";");

                while (st.hasMoreTokens()) {
                    lineCount++;
                    String token = st.nextToken();
                    if (token.equals("NextGS")) {
                        GSCount++;
                        Main.globalScenes.add(new ArrayList<String[]>());
                    } else {
                        String token2 = st.nextToken();
                        String token3 = st.nextToken();
                        String[] put = new String[]{token, token2, token3};
                        Main.globalScenes.get(GSCount).add(put);
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println("Error with file: " + ex + " Filename: currentProjectGS.txt");
        }

        //loading GS names
        File descFile7 = new File(strDirectoryProjectConfig, "currentProjectGSnames.txt");
        try {
            System.out.println("Sucessfully accessed txt file: " + descFile7);
            FileReader fr = new FileReader(descFile7);
            BufferedReader br = new BufferedReader(fr);
            String dbRecord;
            int lineCount = 0;

            Main.globalSceneName.removeAll(Main.globalSceneName);

            while ((dbRecord = br.readLine()) != null) {
                //accessing file
                lineCount++;
                Main.globalSceneName.add(dbRecord);
            }
        } catch (Exception ex) {
            System.out.println("Error with file: " + ex + " Filename: currentProjectGSnames.txt");
        }
    }

    public void saveVariablesToFile() {
        //function that saves variables into .txt files that will allow to remember existing project
        //saving Main.allLights
        String txtName = "currentProjectLights.txt";
        File f = new File(strDirectoryProjectConfig, txtName);
        try {
            FileWriter fstream = new FileWriter(f);
            BufferedWriter out = new BufferedWriter(fstream);
            //for every CL
            String line = "";
            for (int j = 0; j < Main.allLights.size(); j++) {
                line = Main.allLights.get(j)[0] + ";" + Main.allLights.get(j)[1] + ";" + Main.allLights.get(j)[2] + ";" + Main.allLights.get(j)[3] + ";" + Main.allLights.get(j)[4] + ";";
                out.write(line);
                out.newLine();
            }
            out.close();
            System.out.println("File saved successfully: " + f);
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

        //saving Main.freeFloorNumbers
        String txtName5 = "currentProjectFreeFloors.txt";
        File f5 = new File(strDirectoryProjectConfig, txtName5);
        try {
            FileWriter fstream = new FileWriter(f5);
            BufferedWriter out = new BufferedWriter(fstream);
            //for every free floor
            String line = "";
            for (int j = 0; j < Main.freeFloorNumbers.size(); j++) {
                line = Main.freeFloorNumbers.get(j) + "";
                out.write(line);
                out.newLine();
            }
            out.close();
            System.out.println("File saved successfully: " + f5);
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

        //saving Main.allUnits
        String txtName2 = "currentProjectUnits.txt";
        File f2 = new File(strDirectoryProjectConfig, txtName2);
        try {
            FileWriter fstream2 = new FileWriter(f2);
            BufferedWriter out2 = new BufferedWriter(fstream2);
            //for every CL
            String line = "";
            String line0 = "";
            for (int j = 0; j < Main.allUnits.size(); j++) {
                line0 = "NextFloor;";
                out2.write(line0);
                out2.newLine();
                for (int i = 0; i < Main.allUnits.get(j).size(); i++) {
                    line = Main.allUnits.get(j).get(i)[0] + ";" + Main.allUnits.get(j).get(i)[1] + ";" + Main.allUnits.get(j).get(i)[2] + ";";
                    out2.write(line);
                    out2.newLine();
                }
            }
            out2.close();
            System.out.println("File saved successfully: " + f5);
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

        //saving Main.floorDescriptions
        String txtName3 = "currentProjectDescriptions.txt";
        File f3 = new File(strDirectoryProjectConfig, txtName3);
        try {
            FileWriter fstream3 = new FileWriter(f3);
            BufferedWriter out3 = new BufferedWriter(fstream3);
            //for every CL
            String line = "";
            for (int i = 1; i < Main.floorDescriptions.size(); i++) {
                line = Main.floorDescriptions.get(i);
                out3.write(line);
                out3.newLine();
            }
            out3.close();
            System.out.println("File saved successfully: " + f5);
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

        //saving Main.floorImages
        String txtName4 = "currentProjectImages.txt";
        File f4 = new File(strDirectoryProjectConfig, txtName4);
        try {
            FileWriter fstream3 = new FileWriter(f4);
            BufferedWriter out3 = new BufferedWriter(fstream3);
            //for every CL
            String line = "";
            for (int i = 1; i < Main.floorImages.size(); i++) {
                line = Main.floorImages.get(i);
                out3.write(line);
                out3.newLine();
            }
            out3.close();
            System.out.println("File saved successfully: " + f5);
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
        //saving Main.globalScenes
        String txtName6 = "currentProjectGS.txt";
        File f6 = new File(strDirectoryProjectConfig, txtName6);
        try {
            FileWriter fstream2 = new FileWriter(f6);
            BufferedWriter out2 = new BufferedWriter(fstream2);
            //for every GS
            String line = "";
            String line0 = "";
            for (int j = 0; j < Main.globalScenes.size(); j++) {
                line0 = "NextGS;";
                out2.write(line0);
                out2.newLine();
                for (int i = 0; i < Main.globalScenes.get(j).size(); i++) {
                    line = Main.globalScenes.get(j).get(i)[0] + ";" + Main.globalScenes.get(j).get(i)[1] + ";" + Main.globalScenes.get(j).get(i)[2] + ";";
                    out2.write(line);
                    out2.newLine();
                }
            }
            out2.close();
            System.out.println("File saved successfully: " + f6);
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

        //saving Main.globalSceneName
        String txtName7 = "currentProjectGSnames.txt";
        File f7 = new File(strDirectoryProjectConfig, txtName7);
        try {
            FileWriter fstream3 = new FileWriter(f7);
            BufferedWriter out3 = new BufferedWriter(fstream3);
            //for every GS
            String line = "";
            for (int i = 0; i < Main.globalSceneName.size(); i++) {
                line = Main.globalSceneName.get(i);
                out3.write(line);
                out3.newLine();
            }
            out3.close();
            System.out.println("File saved successfully: " + f7);
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }

    static public boolean emptyDirectory(File path) {
        //removing all files from directory specified in argument
        if (path.exists()) {
            File[] files = path.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    emptyDirectory(files[i]);
                } else {
                    try {
                        if (files[i].delete()) {
                            System.out.println("File " + files[i].getAbsolutePath() + " was deleted.");
                        } else {
                            System.out.println("File " + files[i].getAbsolutePath() + " wasn't deleted. Problem occured.");
                        }
                    } catch (Exception ex) {
                        System.err.println("Unable to delete " + files[i] + "(" + ex.getMessage() + ")");
                    }
                }
            }
        }
        return (true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        //setting Windows Look and Feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println("Error setting native LAF: " + ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                WelcomeScreen thisFrame = new WelcomeScreen();
                String[] vars = null;
                Main.main(vars);
                Main.changeFrame(thisFrame);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Cancel;
    private javax.swing.JFrame ClosingConfirmation;
    private javax.swing.JButton OK;
    private javax.swing.JButton existingProjectButton;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JFileChooser fileChooser2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JButton newProjectButton;
    private javax.swing.JButton openProjectFileButton;
    private javax.swing.JButton quitButton;
    // End of variables declaration//GEN-END:variables
}
